import storage from './storage';
import config from '../config';
import store from '../store';

/**
 * 工具类
 * @type {{}}
 */
let util = {

};

/**
 * 修改网页title
 * @param title
 */
util.title = function (title) {
    title = title || '首页';
    window.document.title = title;
};

/**
 * 设置axios配置，增加csrf-token配置
 * @type {string}
 */
window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

/**
 * ajax baseURL 配置
 * @type {string}
 */
const ajaxUrl = config.ajaxUrl;
util.ajax = window.axios.create({
    baseURL: ajaxUrl,
    timeout: 30000
});

/**
 * ajax api baseURL 配置
 * @type {string}
 */
const getApiAxios = () => {
    const apiUrl = config.apiUrl;
    const tokens = storage.get('tokens') || {};
    const instance = axios.create({
        baseURL: apiUrl,
        timeout: 30000,
        headers: {
            'Authorization': 'Bearer ' + tokens.access_token,
            'RefreshToken': tokens.refresh_token,
        }
    });

    instance.interceptors.response.use(
        response => {
            if (response.headers.hasOwnProperty('accesstoken') && response.headers.hasOwnProperty('refreshtoken')) {
                tokens.token_type = response.headers.tokentype;
                tokens.access_token = response.headers.accesstoken;
                tokens.refresh_token = response.headers.refreshtoken;

                storage.set('tokens', tokens);
            }
            return response;
        },

        err => {
            return Promise.reject(err);
        }
    );

    return instance;
};

util.api = getApiAxios;

util.handleApiException = (e, vm, defaultMessage = '网络请求异常') => {
    console.log(e);
    if (e.response) {
        if (e.response.status == 422) {
            if (e.response.data.hasOwnProperty('errors')) {
                for (let i in e.response.data.errors) {
                    vm.$root.topTips(e.response.data.errors[i][0]);
                }
            }
        } else if (e.response.status == 401) {
            if (e.response.hasOwnProperty('data')) {
                vm.$root.topTips(e.response.data.message);
            } else {
                vm.$root.topTips('用户名或密码错误');
            }
            vm.$store.commit('logout');
            vm.$router.push({
                name: 'login'
            })
        } else {
            vm.$root.topTips(e.response.data.message);
        }
    }  else {
        vm.$root.topTips(defaultMessage);
    }
};

util.isLogin = function () {
    const user = storage.get('user');
    if ((user && user !== undefined && user !== null) && user.hasOwnProperty('id')) {
        const tokens = storage.get('tokens');
        store.commit('setTokens', tokens);
        store.commit('setUser', user);
    }
};

util.isWeixinBrowser = function () {
    let ua = window.navigator.userAgent.toLowerCase();
    let res = ua.match(/MicroMessenger/i);
    if (res && res.indexOf('micromessenger') != -1) {
        return true;
    } else {
        return false;
    }
}

util.isAlipayBrowser = function () {
    let ua = window.navigator.userAgent.toLowerCase();
    let res = ua.match(/Alipay/i).indexOf('alipay');
    if (res && res.indexOf('alipay') != -1) {
        return true;
    } else {
        return false;
    }
}

/**
 * 刷新accessToken
 */
util.refreshToken = function () {
    const tokens = storage.get('tokens');
    var form_params = {
        'grant_type': 'refresh_token',
        'client_id': config.appId,
        'client_secret': config.appSecret,
        'refresh_token': tokens.refresh_token,
        'scope': ''
    };

    util.ajax.post('/oauth/token', form_params).then((resp) => {
        storage.set('tokens', resp.data);
        store.dispatch('setTokens', resp.data);
        console.log('自动刷新Token成功');
    }).catch((e) => {
        console.log('自动刷新Token失败', e);
    });
};

/**
 * 判断数组是否存在另一个数组中
 * @param arr
 * @param targetArr
 * @returns {boolean}
 */
util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

/**
 * 判断元素是否存在指定数组中
 * @param ele
 * @param targetArr
 * @returns {boolean}
 */
util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

export default util;